import { onLoad, onShow } from "@dcloudio/uni-app"
import { getCurrentInstance, onMounted, reactive, ref, watch } from "vue"
import { mySendTimeRule, objectAny, PackCategoriesRule } from "../../options/base";
import { myConfigStore, myPackCategoriesStore, mySchoolStore, mySendTimeStore, myTipsMoneyStore } from "../../store";
import { getMySelf, getYiZhanAddressList } from "../../utils/doCloud";
import { goToPage, showModal, showToast } from "../../utils/utils";

function createPacksDefaultData() {
	return {
		pack: {
			id: ``,
			pack_type: 0,
			moeny: ``,
			add_money: ``
		},
		verify_code: ``,
		fast_status: false,
	}
}


type totalMoneyDescListRule = Array<{
	verify_code : string;
	moeny : string;
}>
type sendTimeCheckItRule = {
	alias_text ?: string;
	disable : boolean;
	max : number;
	min : number;
	text : string;
	value : number
}
interface sendTimeRightListRule {
	others : {
		alias_first_time : string;
		alias_name : string;
		checked : sendTimeCheckItRule;
		create_date : number;
		enable : boolean;
		end_time : number;
		name : string;
		school_id : string;
		send_date : string;
		splice_mode : number;
		splice_time : objectAny;
		start_time : number;
		_id : string;
	};
	list : Array<sendTimeCheckItRule>
}

export default {
	setup() {
		let onLoadLoaddingEnd = false;   //是否在onLoad下数据已经加载完成

		const myConfig = myConfigStore()
		const sendTimeStore = mySendTimeStore();
		const tipsMoneyStore = myTipsMoneyStore();
		const myPackStore = myPackCategoriesStore()
		const schoolStore = mySchoolStore();

		let defaultSendTime : sendTimeRightListRule[`others`] = {} as sendTimeRightListRule[`others`];   //默认的预计送达时间全局接收器 由服务器提供数据
		let defaultTips : objectAny = {}  //默认的打赏数据全局接收器 由服务器提供数据

		const orderReady = ref(false);
		const protocolStatus = ref(true);
		const showBillingStatus = ref(false);
		const swiperDotIndex = ref(0);
		const menusMaxCount = ref(3);
		const sendTimeRightList = ref<sendTimeRightListRule>({
			others: {} as sendTimeRightListRule[`others`],
			list: []
		})
		const totalMoney = ref(0);
		const totalMoneyDesc = ref({
			base: {
				total: 0,
				list: [] as totalMoneyDescListRule
			},
			add: {
				total: 0,
				list: [] as totalMoneyDescListRule
			},
			tipsMoney: 0
		})
		const formData = reactive({
			menu_id: ``,
			yizhan: {
				_id: ``,
				name: `取件地址信息`,
				all_desc: `点击选择取件地址`
			},
			get: {
				_id: ``,
				name: `收件人信息`,
				moblie: ``,
				address: `点击选择收货地址`
			},
			user_remark: ``,
			base: {
				send_time: {
					_id: ``,
					html_menus_id: ``,
					checked: {}
				},
				some_tips: {
					money: ``,
					_id: ``,
					cacheMoney: ``
				},
				connect_phone: ``
			},
			packs: [createPacksDefaultData()]
		})

		const bottomPopupRef0 = ref(null)       // 明细弹窗说明
		const bottomPopupRef1 = ref(null)       //加急弹窗说明
		const bottomPopupRef2 = ref(null)       // 小费弹窗说明
		const bottomPopupRef3 = ref(null)         //预计送达弹框
		const swipeActionRef = ref(null)

		const yiZhanAddressList = getYiZhanAddressList();        //取件驿站地址

		watch(formData, () => { computedOrderReadyStatus() })
		watch(formData.base, () => { computedTotalMoney() });
		watch(formData.packs, (value) => {
			const refsList = swipeActionRef.value as any
			if (Object.keys(value).length === 1) {
				for (let key in refsList) {
					refsList[key].closeAll();
				}
			}
			computedTotalMoney();
		})

		Promise.all([
			new Promise<void>((resolve) => {
				onLoad((options) => {
					uni.setNavigationBarTitle({
						title: options.title || '一统云校'
					});
					formData.menu_id = options.id || '';
					resolve();
				})
			}),
			new Promise<void>(resolve => {
				onShow(() => {
					onShowInit();
					resolve();
				})
			})
		]).then(async () => {
			await onLoadInit();
			onLoadLoaddingEnd = true;
			onShowInit();
		})

		async function onLoadInit() {
			const schoolId = schoolStore.mySchool._id
			await Promise.all([
				sendTimeStore.getSendTime(schoolId),
				tipsMoneyStore.getTipsMoney(schoolId),
				myPackStore.getPackCategories(schoolId)
			])

			if (!sendTimeStore?.mySendTime?.length) {
				// 如果没有提前设置预选项 就不加载
				return
			}

			const { splice_time_text, splice_time, ...otherData } = createDefaultSendTime() as mySendTimeRule;
			const [checkedTips] = tipsMoneyStore.myTipsMoney;
			defaultSendTime = otherData as sendTimeRightListRule[`others`];
			defaultTips = checkedTips

			sendTimeRightList.value = {
				others: defaultSendTime,
				list: splice_time_text as Array<sendTimeCheckItRule>
			}

			formData.base = {
				send_time: {
					...defaultSendTime,
					html_menus_id: defaultSendTime?._id
				},
				some_tips: {
					money: ``,
					_id: defaultTips && defaultTips._id || ``,
					cacheMoney: defaultTips && defaultTips.money || ``
				},
				connect_phone: ``
			}
		}

		async function onShowInit() {
			if (!onLoadLoaddingEnd) {
				return console.log(`xxxxxx=> onLoad下数据未加载完成，取消本次onShow需要做的事情 <=xxxxxx`)
			}
			const addressSelect = uni.getStorageSync(`selectAddress`);
			const packSelect = uni.getStorageSync(`packCategoriesSelect`);
			uni.removeStorageSync(`packCategoriesSelect`);
			uni.removeStorageSync(`selectAddress`);
			if (packSelect) {
				const { id, selectIndex } = JSON.parse(packSelect);
				const item : PackCategoriesRule[0] | {} = await myPackStore.idFindPack(id);
				if (Object.keys(item).length > 0) {
					const { _id, pack_type, moeny, add_money } = item as PackCategoriesRule[0];
					formData.packs[selectIndex].pack = {
						id: _id,
						pack_type,
						moeny,
						add_money
					}
				}
			}

			if (addressSelect) {
				const { _id, name, address, moblie } = JSON.parse(addressSelect);
				formData.get = {
					_id,
					name,
					moblie,
					address: `${schoolStore.mySchool.school_name} - ${address}`
				}
			}
		}

		function createDefaultSendTime() {
			const list = sendTimeStore.mySendTime.sort((a : any, b : any) => {
				return a.start_time - b.start_time
			});

			const item = list[0];
			const checked = item.splice_time_text[0];

			const { splice_time_text, alias_first_time } = item

			if (item.alias_first_time.trim() !== ``) {
				item.splice_time_text[0].alias_text = alias_first_time
			}
			return {
				...item,
				checked,
			}
		}

		const computedOrderReadyStatus = () => {
			orderReady.value = false;
			const { yizhan, get, base, packs } = formData
			if (yizhan._id === ``
				|| get._id === ``
				|| base.send_time._id === ``
				|| !protocolStatus.value
			) {
				return false
			}

			for (let i = 0; i < packs.length; i++) {
				const it = packs[i];
				if (it.pack.id === `` || it.verify_code === ``) {
					return false
				}
			}

			orderReady.value = true;
		}

		const computedTotalMoney = () => {
			const value = formData.packs;

			let total = 0
			const base = {
				total: 0 as number,
				list: [] as totalMoneyDescListRule
			}
			const add = {
				total: 0 as number,
				list: [] as totalMoneyDescListRule
			}
			for (let i = 0; i < value.length; i++) {
				const it = value[i];
				if (it.verify_code !== '') {

					total += (+it.pack.moeny);
					base.total += (+it.pack.moeny)
					base.list.push({
						moeny: it.pack.moeny,
						verify_code: it.verify_code
					});

					if (it.fast_status) {
						total += (+it.pack.add_money);
						add.total += (+it.pack.add_money);
						add.list.push({
							moeny: it.pack.add_money,
							verify_code: it.verify_code
						})
					}
				}
			}
			const tipsMoney = formData.base.some_tips.money
			if (tipsMoney !== '') {
				total += (+tipsMoney)
				totalMoneyDesc.value.tipsMoney = (+tipsMoney)
			}
			totalMoney.value = total;
			totalMoneyDesc.value.add = add;
			totalMoneyDesc.value.base = base;
		}

		const menusRemove = async (index : number) => {
			const status = await showModal({
				title: `安全提示`,
				content: `你确定要删除改栏目？`
			})
			if (status) {
				formData.packs.splice(index, 1)
			}
		}

		const addMoreInfoBox = () => {
			formData.packs.push(createPacksDefaultData())
		}

		const checkTipsMoney = () => {
			const { cacheMoney } = formData.base.some_tips;
			formData.base.some_tips.money = cacheMoney;
			(bottomPopupRef2.value as any).close()

		}
		const setDefaultTipsMoney = () => {
			const some_tips = formData.base.some_tips;
			if (some_tips.money === ``) {
				formData.base.some_tips = {
					money: ``,
					_id: defaultTips && defaultTips._id || ``,
					cacheMoney: defaultTips && defaultTips.money || ``
				}
			}
			(bottomPopupRef2.value as any).open()
		}

		const sendTimeBarToggle = (it : mySendTimeRule) => {
			if (it.alias_first_time.trim() !== ``) {
				it.splice_time_text[0].alias_text = it.alias_first_time
			}
			const { splice_time_text, splice_time, ...othersData } = it;

			formData.base.send_time.html_menus_id = othersData._id;
			sendTimeRightList.value = {
				others: othersData as sendTimeRightListRule[`others`],
				list: it.splice_time_text as Array<sendTimeCheckItRule>
			}
		}
		const checkedSendTime = (it : mySendTimeRule["splice_time_text"][0]) => {
			formData.base.send_time = {
				...sendTimeRightList.value.others,
				checked: it,
				html_menus_id: formData.base.send_time.html_menus_id
			};
			(bottomPopupRef3.value as any).close();
		}

		const needFastStatusChange = (e : any, index : number) => {
			const status = e.detail.value;
			formData.packs[index].fast_status = status;
			if (status) {
				(bottomPopupRef1.value as any).open()
			} else {
				(bottomPopupRef1.value as any).close()
			}
		}

		const showBillingDesc = () => {
			showBillingStatus.value = !showBillingStatus.value;
			if (showBillingStatus.value) {
				(bottomPopupRef0.value as any).open()
			} else {
				(bottomPopupRef0.value as any).close()
			}

		}

		const showActionSheet = async () => {
			const list = await yiZhanAddressList;
			 
			const itemList = list.map(it => it.name)
			uni.showActionSheet({
				title: `取件地址`,
				itemList,
				success: ({ tapIndex }) => {
					const item = list[tapIndex as number];
					formData.yizhan = {
						_id: item._id,
						name: item.name,
						all_desc: item.desc
					}
				}
			});
		}

		const protocolChange = (e : any) => {
			const values = e.detail.value;
			protocolStatus.value = values.length > 0;
			computedOrderReadyStatus();
		}

		const confimOrder = async () => {

			const { yizhan, get, base, packs } = formData
			const list = packs.filter(it => it.pack.id === `` || it.verify_code === ``)

			if (yizhan._id === ``) {
				return showToast(`请选择取件地址信息`, "none")
			}
			if (get._id === ``) {
				return showToast(`请选择收货人信息`, "none")
			}
			if (base.send_time._id === ``) {
				return showToast(`请选择预计送达时间`, "none")
			}
			if (list.length > 0) {
				const { verify_code, pack } = list[0];
				if (pack.id == ``) {
					return showToast(`请先选择物件大小`, "none")
				}
				if (verify_code == ``) {
					return showToast(`请填写物件取件码`, "none")
				}
			}
			if (!protocolStatus.value) {
				return showToast(`请阅读并同意跑腿协议`, "none")
			}
			if (!orderReady.value) {
				return showToast(`请填写完整的取件信息`, "none");
			}

			const orderManage = uniCloud.importObject(`admin-order-manage`)
			const { _id } = await getMySelf();

			try {
				const { errCode, errMsg, data } = await orderManage.createOrder({
					...formData,
					user_id: _id,
					school_id: schoolStore.mySchool._id
				});
				console.log(data)
				if (errCode === 0) {
					goToPage({
						path: `/common/orderCounter/orderCounter`,
						navType: `push`,
						params: {
							order_id: data.order_id,
							module: `runErrand`
						}
					})
				} else {
					showModal({
						title: `异常提示`,
						content: errMsg,
						showCancel: false
					})
				}
			} catch (error) {
				showModal({
					title: `异常提示`,
					content: `下单异常，请联系管理员`,
					showCancel: false
				})
			}

		}

		return {
			orderReady,
			protocolStatus,
			totalMoney,
			formData,
			showBillingStatus,
			swiperDotIndex,
			bottomPopupRef0,
			bottomPopupRef1,
			bottomPopupRef2,
			swipeActionRef,
			bottomPopupRef3,
			menusMaxCount,
			sendTimeStore,
			tipsMoneyStore,
			sendTimeRightList,
			myPackStore,
			myConfig,
			totalMoneyDesc,
			protocolChange,
			confimOrder,
			goToPage,
			needFastStatusChange,
			menusRemove,
			addMoreInfoBox,
			showBillingDesc,
			showActionSheet,
			checkedSendTime,
			sendTimeBarToggle,
			setDefaultTipsMoney,
			checkTipsMoney,
		}
	}
}